package com.ruoyi.web.controller.boc;

import com.ruoyi.boc.config.SmsConfig;
import com.ruoyi.boc.domain.BocCommonParams;
import com.ruoyi.boc.domain.BocFilesWithDates;
import com.ruoyi.boc.service.IBocCommonService;
import com.ruoyi.boc.service.IBocLdapService;
import com.ruoyi.boc.utils.BocFileUploadUtils;
import com.ruoyi.boc.utils.SendSmsUtils;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.system.service.ISysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/boc/common")
public class BocCommonController extends BaseController {
    @Value("${ruoyi.profile}")
    private String uploadPath;
    @Resource
    private SmsConfig smsConfig;
    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private IBocCommonService commonService;
    @Autowired
    private ISysMenuService menuService;
    @Autowired
    private IBocLdapService lBocLdapService;

    @PreAuthorize("@ss.hasPermi('boc:common:upload')")
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception {
        System.out.println("进入自定义上传");
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath() + "/code";
            // 上传并返回新文件名称
            String fileName = BocFileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 查看上传的文件
     */

    @PreAuthorize("@ss.hasPermi('boc:common:upload')")
    @GetMapping("/listFilesWithDates")
    public AjaxResult listFilesWithDates(BocCommonParams bocCommonParams) {
        List<BocFilesWithDates> list = new ArrayList<BocFilesWithDates>();
        //String directoryPath = "D:\\ruoyi\\uploadPath\\upload\\code";
        String directoryPath = RuoYiConfig.getUploadPath() + "/code";
        // 使用 File 类获取目录对象
        File directory = new File(directoryPath);
        // 获取目录下的所有文件和子目录
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                // 获取文件的绝对路径
                Path filePath = Paths.get(file.getAbsolutePath());
                // 获取文件的详细信息
                try {
                    BasicFileAttributes attrs = Files.readAttributes(filePath, BasicFileAttributes.class);
                    // 获取文件的修改时间
                    Date lastModifiedTime = new Date(attrs.lastModifiedTime().toMillis());
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String formattedDate = sdf.format(lastModifiedTime);
                    // 打印文件名和修改时间
                    //System.out.println("File: " + file.getName() + ", Modified Date: " + formattedDate);
                    BocFilesWithDates bocFilesWithDates = new BocFilesWithDates();
                    bocFilesWithDates.setFileName(file.getName());
                    bocFilesWithDates.setFileDate(formattedDate);
                    list.add(bocFilesWithDates);
                } catch (IOException e) {
                    System.err.println("Error reading attributes for file: " + file.getName());
                    e.printStackTrace();
                }
            }
        } else {
            System.out.println("The directory is empty or an error occurred.");
        }
        return success(list);
    }

    @PreAuthorize("@ss.hasPermi('boc:common:checkUsers')")
    @GetMapping("/getCheckUsers")
    public AjaxResult getApproveUsers() {
        System.out.println("获取复核用户信息");
        String userName = getUsername();
        HashMap params = new HashMap();
        params.put("userName", userName);
        HashMap userInfoMap = commonService.findUserInfo(params);
        String deptId = userInfoMap.get("deptId").toString();
        String orgIdr = userInfoMap.get("orgIdr").toString();
        String superiors = userInfoMap.get("superiors").toString();
        String[] deptIds = superiors.split(",");

        if (orgIdr.equals("0") || orgIdr.equals("24")) {
            System.out.println("营业网点");
            params.clear();
            params.put("deptIds", deptId);
            return success(commonService.selectCheckUsers(params));
        } else {
            System.out.println("非营业网点");
            userInfoMap.clear();
            params.put("deptIds", superiors);
            return success(commonService.selectCheckTeamUsers(params));
        }
    }

    @PreAuthorize("@ss.hasPermi('boc:common:empowerUsers')")
    @GetMapping("/getEmpowerUsers")
    public AjaxResult getAuthUsers() {
        System.out.println("获取授权用户信息");
        String userName = getUsername();
        HashMap params = new HashMap();
        params.put("userName", userName);
        HashMap userInfoMap = commonService.findUserInfo(params);
        String deptId = userInfoMap.get("deptId").toString();
        String orgIdr = userInfoMap.get("orgIdr").toString();
        String superiors = userInfoMap.get("superiors").toString();
        String[] deptIds = superiors.split(",");
        params.put("deptIds", superiors);
        return success(commonService.selectEmpowerUsers(params));
    }


    /**
     * 获取菜单下拉树列表
     */

    @PreAuthorize("@ss.hasPermi('boc:common:authMenu')")
    @GetMapping("/getAuthMenu")
    public AjaxResult getAuthMenu() {
        HashMap params = new HashMap();
        if (getUserId() != 1) {
            params.put("userId", getUserId());
        }
        List<SysMenu> menus = commonService.selectAuthMenuList(params);
        return success(menuService.buildMenuTreeSelect(menus));
    }

    /**
     * 获取菜单下拉树列表
     */

    @PreAuthorize("@ss.hasPermi('boc:common:rptIsAuth')")
    @GetMapping("/findRptIsAuth/{menuPath}")
    public AjaxResult findRptIsAuth(@PathVariable("menuPath") String menuPath) {
        HashMap params = new HashMap();
        params.put("menuPath", menuPath);
        params.put("userId", getUserId());
        HashMap rptIsAuthMap = commonService.findRptIsAuth(params);
        return success(rptIsAuthMap == null ? "no" : "yes");
    }

    /**
     * 验证用户下载密码
     */

    @PreAuthorize("@ss.hasPermi('boc:common:authValida')")
    @PostMapping("/authValida")
    public AjaxResult authValida(@RequestBody BocCommonParams bocCommonParams) {
        System.out.println("验证用户下载密码");
        //System.out.println(lBocLdapService.authenticate(getUsername(), bocCommonParams.getPassword()));
        return success(lBocLdapService.authenticate(getUsername(), bocCommonParams.getPassword()) ? "yes" : " no");
    }

    /**
     * 短信发送
     */

    @PreAuthorize("@ss.hasPermi('boc:common:sendSms')")
    @PostMapping("/sendSms")
    public AjaxResult sendSms(@RequestBody BocCommonParams bocCommonParams) throws Exception {
        System.out.println("验证用户下载密码");
        String mobile = bocCommonParams.getMobile().trim();
        String message =  bocCommonParams.getMessage().trim();
        if(!SendSmsUtils.isValidPhoneNumber(mobile)){
            return error("手机号码格式错误");
        }else if(message.equals("")){
            return error("发送信息不能为空");
        }
        Boolean sendFlat = SendSmsUtils.sendSms(smsConfig.getHost(),smsConfig.getPort(),mobile,message);
        if(sendFlat){
            return success("信息发送成功");
        }
        return error("信息发送失败");
    }
}

